package com.sunxd.vue.infrastructure.interceptors;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.sunxd.vue.bean.Response;
import com.sunxd.vue.domain.bean.enums.ErrorEnum;
import com.sunxd.vue.domain.exception.InternalServerException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author sun.xd
 * @description: description
 * @date 2024/4/2 16:53
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        if(StringUtils.isBlank(token)){
            response.getWriter().write(JSON.toJSONString(Response.createError(ErrorEnum.NOT_LOGIN)));
            return false;
        }
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("!Q@W#E$R")).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        Map<String, Claim> claims = decodedJWT.getClaims();
        if(!claims.containsKey("user")){
            response.sendError(500, JSON.toJSONString(Response.createError(ErrorEnum.LOGIN_ERR)));
            return false;
        }
        return true;
    }
}
